from datetime import datetime, timedelta
import pandas as pd
from pymongo import MongoClient
from collections import defaultdict

# MongoDB连接配置
MONGO_URI = 'mongodb://localhost:27017/'
DATABASE_NAME = 'test'


def connect_to_mongodb(uri, db_name):
    """连接到MongoDB"""
    try:
        client = MongoClient(uri)
        db = client[db_name]
        print(f"成功连接到MongoDB数据库: {db_name}")
        return db
    except Exception as e:
        print(f"连接MongoDB失败: {e}")
        return None


def analyze_user_reading_activity(db):
    """
    分析日志数据获取活跃用户阅读数据
    返回结构: {
        'active_users': [活跃用户列表],
        'popular_books': [热门图书列表],
        'reading_trends': 阅读趋势数据
    }
    """
    try:
        # 1. 获取最近30天的日志数据
        cutoff_date = datetime.now() - timedelta(days=30)
        logs = list(db['logs'].find({
            'timestamp': {'$gte': cutoff_date},
            'action': {'$in': ['read', 'collect', 'review']}
        }))

        if not logs:
            print("没有找到近期的阅读日志数据")
            return None

        print(f"获取到 {len(logs)} 条近期阅读日志")

        # 2. 分析活跃用户
        user_activity = defaultdict(lambda: {
            'read_count': 0,
            'collect_count': 0,
            'review_count': 0,
            'last_active': datetime.min,
            'books': set()
        })

        for log in logs:
            user_id = log['u_id']
            action = log['action']
            book_id = log['b_id']
            timestamp = log['timestamp']

            # 更新用户活动统计
            user_activity[user_id]['books'].add(book_id)
            user_activity[user_id]['last_active'] = max(
                user_activity[user_id]['last_active'],
                timestamp
            )

            if action == 'read':
                user_activity[user_id]['read_count'] += 1
            elif action == 'collect':
                user_activity[user_id]['collect_count'] += 1
            elif action == 'review':
                user_activity[user_id]['review_count'] += 1

        # 3. 获取用户详细信息
        active_users = []
        for user_id, stats in user_activity.items():
            user = {
                'id': user_id
            }

            active_users.append({
                'u_id': user_id,
                'read_count': stats['read_count'],
                'collect_count': stats['collect_count'],
                'review_count': stats['review_count'],
                'book_count': len(stats['books']),
                'last_active': stats['last_active']
            })

        # 4. 分析热门图书
        book_popularity = defaultdict(lambda: {
            'read_count': 0,
            'collect_count': 0,
            'review_count': 0,
            'unique_users': set()
        })

        for log in logs:
            book_id = log['b_id']
            user_id = log['u_id']
            action = log['action']

            book_popularity[book_id]['unique_users'].add(user_id)

            if action == 'read':
                book_popularity[book_id]['read_count'] += 1
            elif action == 'collect':
                book_popularity[book_id]['collect_count'] += 1
            elif action == 'review':
                book_popularity[book_id]['review_count'] += 1

        # 5. 获取图书详细信息
        popular_books = []
        for book_id, stats in book_popularity.items():
            book = {
                '_id': book_id
            }

            popular_books.append({
                'id': book_id,
                'read_count': stats['read_count'],
                'collect_count': stats['collect_count'],
                'review_count': stats['review_count'],
                'unique_users': len(stats['unique_users'])
            })

        # 6. 分析阅读趋势（按天统计）
        daily_reading = defaultdict(int)
        for log in logs:
            if log['action'] == 'read':
                date = log['timestamp'].strftime('%Y-%m-%d')
                daily_reading[date] += 1

        reading_trends = sorted([
            {'date': date, 'count': count}
            for date, count in daily_reading.items()
        ], key=lambda x: x['date'])

        # 7. 返回分析结果
        return {
            'active_users': sorted(
                active_users,
                key=lambda x: x['read_count'],
                reverse=True
            )[:50],  # 取前50名活跃用户
            'popular_books': sorted(
                popular_books,
                key=lambda x: x['read_count'],
                reverse=True
            )[:50],  # 取前50本热门图书
            'analysis_time': datetime.now()
        }

    except Exception as e:
        print(f"分析阅读活动数据时出错: {e}")
        return None


def save_analysis_results(db, analysis_data):
    """保存分析结果到MongoDB"""
    try:
        db['reading_analysis'].delete_many({})
        db['reading_analysis'].insert_one({
            'active_users': analysis_data['active_users'],
            'popular_books': analysis_data['popular_books'],
            'generated_at': analysis_data['analysis_time']
        })
        print("成功保存阅读分析结果到数据库")
    except Exception as e:
        print(f"保存分析结果失败: {e}")


def main():
    # 连接MongoDB
    db = connect_to_mongodb(MONGO_URI, DATABASE_NAME)

    # 分析日志数据
    analysis_data = analyze_user_reading_activity(db)

    # 保存分析结果
    save_analysis_results(db, analysis_data)



if __name__ == "__main__":
    main()